package domain.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import domain.data.QnAPersistenceManager;
import domain.model.Domain;


public class Ip {
	public Ip(String name_domain)
	{
		String content = "";
		try {
			PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();

			URL dataURL = new URL("http://domaintoip.com/ip.php?domain="+name_domain);
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(dataURL.openStream(), Charset.forName("UTF8")));
			
			while(1==1)
			{
				String str = reader.readLine();
				if(str==null) break;
				content+=str;
				
			}
			
			Document doc = Jsoup.parse(content);

			String ip=null;
			try {
				ip = doc.select("h2[class=h2]").html().replaceAll("\\<.*?\\>", "<br/>");
				
				String[] listIp = ip.split("\n");
				if(listIp.length > 0)
				{
					for(int i=0;i<listIp.length;i++)
					{
						PersistenceManager psms = QnAPersistenceManager.get().getPersistenceManager();
						@SuppressWarnings("unchecked")
						List<domain.model.TrackIp> ips=  (List<domain.model.TrackIp>)psms.newQuery(domain.model.TrackIp.class,"ip == '"+listIp[i]+"'").execute();
						if(ips.size() > 0)
						{
							ips.get(0).addDomain(name_domain);
							psms=JDOHelper.getPersistenceManager(ips.get(0));
							psms.currentTransaction().begin();
							psms.makePersistent(ips.get(0));
							psms.currentTransaction().commit();
						} else {
							domain.model.TrackIp track = new domain.model.TrackIp();
							track .addDomain(name_domain);
							track.setIp(listIp[i]);
							psm.makePersistent(track);
						}
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			@SuppressWarnings("unchecked")
			List<Domain> domainList=  (List<Domain>)psm.newQuery(Domain.class,"name == '"+name_domain+"'").execute();
			if(domainList.size()>0)
			{
				Domain domain = domainList.get(0);
				
				psm=JDOHelper.getPersistenceManager(domain);
				domain.setIp(ip);
				domain.setLastUpdateDate(new Date());
				psm.currentTransaction().begin();
				psm.makePersistent(domain);
				psm.currentTransaction().commit();
			}
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
//	public static void main( String args[])
//	{
//		new Ip("showsiteinfo.com");
//	}
}
